package com.sz.mes.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.vo.JsonResult;
import com.sz.mes.dto.LatticeGoodsInventoryDTO;
import com.sz.mes.dto.LatticeGoodsQuantity;
import com.sz.mes.entity.LatticeGoodsInventory;
import com.sz.mes.entity.warehouse.LatticeGoods;
import com.sz.mes.mapper.LatticeGoodsInventoryMapper;
import com.sz.mes.mapper.warehouse.LatticeGoodsMapper;
import com.sz.mes.service.LatticeGoodsInventoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
* 商品库存盘点修改记录相关Service实现
* @author hem
* @version 1.0
* @date 2023-08-11
 * Copyright © szhs
*/
@Service
@Slf4j
public class LatticeGoodsInventoryServiceImpl extends BaseCustomServiceImpl<LatticeGoodsInventoryMapper, LatticeGoodsInventory> implements LatticeGoodsInventoryService {

    private final LatticeGoodsMapper latticeGoodsMapper;
    private final LatticeGoodsInventoryMapper latticeGoodsInventoryMapper;

    public LatticeGoodsInventoryServiceImpl(LatticeGoodsMapper latticeGoodsMapper, LatticeGoodsInventoryMapper latticeGoodsInventoryMapper) {
        this.latticeGoodsMapper = latticeGoodsMapper;
        this.latticeGoodsInventoryMapper = latticeGoodsInventoryMapper;
    }

    @Override
    public JsonResult add(LatticeGoodsInventoryDTO entity) {
        for (LatticeGoodsQuantity latticeGoodsQuantity : entity.getLatticeGoodsQuantities()) {
            QueryWrapper<LatticeGoods> wrapper = new QueryWrapper<>();
            wrapper.eq("goods_id",latticeGoodsQuantity.getGoodsId());
            wrapper.eq("warehouse_lattice_id",latticeGoodsQuantity.getWarehouseLatticeId());
            LatticeGoods latticeGoods = latticeGoodsMapper.selectOne(wrapper);
            if(latticeGoods!=null && !latticeGoods.getQuantity().equals(latticeGoodsQuantity.getQuantity())) {
                //插入到数量盘点修改记录
                LatticeGoodsInventory latticeGoodsInventory = new LatticeGoodsInventory();
                latticeGoodsInventory.setGoodsId(latticeGoodsQuantity.getGoodsId());
                latticeGoodsInventory.setWarehouseLatticeId(latticeGoodsQuantity.getWarehouseLatticeId());
                latticeGoodsInventory.setOldQuantity(latticeGoods.getQuantity());
                latticeGoodsInventory.setTrueQuantity(latticeGoodsQuantity.getQuantity());
                latticeGoodsInventoryMapper.insert(latticeGoodsInventory);

                //修改货格商品的数量
                if(latticeGoodsQuantity.getQuantity()==0){
                    latticeGoodsMapper.deleteById(latticeGoods.getId());
                }else {
                    latticeGoods.setQuantity(latticeGoodsQuantity.getQuantity());
                    latticeGoodsMapper.updateById(latticeGoods);
                }
            }
        }
        return JsonResult.OK("修改成功");
    }
}
